﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Domino;

namespace Streambolics.Notes
{
    /// <summary>
    ///     A connection to Notes
    /// </summary>

    public class Connection
    {
        private NotesSession _Session;
        private string _DefaultServer = String.Empty;

        /// <summary>
        ///     Create the connection to Notes.
        /// </summary>
        /// <param name="aPassword">
        ///     The password needed to unlock the ID file.
        /// </param>
        /// <remarks><para>
        ///     The connection uses the last ID file used by the
        ///     Notes client.
        /// </para><para>
        ///     If the provided password is empty, the Notes library
        ///     will prompt the user for one.
        /// </para></remarks>

        public Connection (string aPassword)
        {
            _Session = new NotesSessionClass ();
            _Session.Initialize (aPassword);
        }

        /// <summary>
        ///     The default server to use when opening a database.
        /// </summary>
        
        public string DefaultServer
        {
            get
            {
                return _DefaultServer;
            }
            set
            {
                _DefaultServer = value;
            }
        }

        public Database Open (string aHostAddress, string aDatabaseName)
        {
            return new Database (GetNotesDatabase (aHostAddress,aDatabaseName));
        }

        /// <summary>
        ///     Open the named database on the default server.
        /// </summary>
        /// <param name="aDatabaseName">
        ///     The path of the database, relative to the notes data
        ///     directory.
        /// </param>
        /// <returns>
        ///     The opened database object.
        /// </returns>

        public Database Open (string aDatabaseName)
        {
            return Open (_DefaultServer, aDatabaseName);
        }

        internal NotesDatabase GetNotesDatabase (string aHostAddress, string aDatabaseName)
        {
            var db = _Session.GetDatabase (aHostAddress, aDatabaseName, false);

            if (db == null)
            {
                if (String.IsNullOrEmpty (aHostAddress))
                {
                    throw new Exception (String.Format ("Database {0} not found on local machine", aDatabaseName));
                }
                else
                {
                    throw new Exception (String.Format ("Database {0} not found on server {1}", aDatabaseName, aHostAddress));
                }
            }
            return db;
        }

        internal NotesDatabase GetNotesDatabase (string aDatabaseName)
        {
            return GetNotesDatabase (_DefaultServer, aDatabaseName);
         
        }
    }
}
